package com.hyk.commonLib.common.drawable;


import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by 贺玉琨 on 2019/3/7 0012.
 */

public abstract class BaseFrameAnimDrawable extends BaseAnimDrawable {
    public BaseFrameAnimDrawable() {
        super();
    }

    @Override
    protected ObjectAnimator initAnimator() {
        ObjectAnimator animator = ObjectAnimator.ofInt(this, "currentProgress", 0, (getFrameCnt() - 1) * 10).setDuration(getDuration());
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        //animator.start();
        return animator;
    }

    public void setCurrentProgress(int currentProgress) {
        this.currentProgress = Math.round(currentProgress / 10F);
        invalidateSelf();
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        Rect bounds = getBounds();
        int width = bounds.width();
        int height = bounds.height();
        if (width * height == 0) return;
        Bitmap bitmap = getCurrentBitmap(currentProgress, width, height);
        if (bitmap == null) return;
        canvas.drawBitmap(bitmap, getCenterMatrix(1, bitmap), paint);
    }

    @Nullable
    protected abstract Bitmap getCurrentBitmap(int currentProgress, int width, int height);

    /**
     * @return 单词动画持续毫秒数
     */
    protected abstract long getDuration();

    protected abstract int getFrameCnt();
}
